package com.jfs.envent.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jfs.cmd.SIPCommander;
import com.jfs.entity.Device;
import com.jfs.envent.EventPublisher;
import com.jfs.envent.entity.DeviceOnlineEventEntity;
import com.jfs.envent.entity.MessageKeepAliveEntity;
import com.jfs.health.RegistryDevice;
import com.jfs.service.DeviceService;
import com.jfs.utils.DeviceUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Description 心跳事件监听者
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/26
 */
@Component
@Slf4j
@AllArgsConstructor
public class KeepAliveEventListener implements ApplicationListener<MessageKeepAliveEntity> {
    private final DeviceService deviceService;
    private final SIPCommander sipCommander;
    private final EventPublisher eventPublisher;

    @Override
    @Async
    public void onApplicationEvent(MessageKeepAliveEntity event) {
        try {
            if (log.isDebugEnabled()) {
                log.debug("【设备号:{},设备ip:{},设备端口号:{}】,发送来心跳信息：{}", event.getDeviceID(), event.getIp(), event.getPort(), JSONUtil.toJsonStr(event));
            }
            //1.更新设备注册表中健康信息
            Device device = RegistryDevice.get(event.getDeviceID());
            //设备离线重连逻辑
            if (Objects.isNull(device)) {
                //设备信息重新获取 持久化
                DeviceOnlineEventEntity deviceOnlineEventEntity = new DeviceOnlineEventEntity(this);
                deviceOnlineEventEntity.setDeviceID(event.getDeviceID());
                deviceOnlineEventEntity.setIp(event.getIp());
                deviceOnlineEventEntity.setPort(event.getPort());
                deviceOnlineEventEntity.setTransport(event.getTransport());
                deviceOnlineEventEntity.setRequestEvent(event.getRequestEvent());
                eventPublisher.publish(deviceOnlineEventEntity);
            }
            Device baseDevice = DeviceUtil.createBaseDevice(event);
            RegistryDevice.registry(baseDevice);
            if (log.isDebugEnabled()) {
                log.debug("【设备号:{},设备ip:{},设备端口号:{}】,发送来心跳信息：{},心跳时间为:{}",
                        event.getDeviceID(), event.getIp(), event.getPort(), JSONUtil.toJsonStr(event), baseDevice.getKeepaliveTime());
            }
            //2.更新数据库
            updateDevice(event);
            //3.更新设备通道信息
            sipCommander.catalog(event.getRequestEvent());
        } catch (Exception e) {
            log.error("设备心跳事件发生异常:{}", e.getMessage());
            e.printStackTrace();
        }
    }


    public void updateDevice(MessageKeepAliveEntity event) {
        this.deviceService.update(Wrappers.<Device>lambdaUpdate()
                .set(Device::getKeepaliveTime, DateUtil.date())
                .set(Device::getOnline, true)
                .eq(Device::getDeviceId, event.getDeviceID()));
    }
}
